package com.hugeyurt.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileUploadController
{
    @PostMapping("/upload")
    public String uploadFile(@RequestPart("file") MultipartFile  file) {
        // 获取上传的文件名

        String fileName = file.getOriginalFilename();
        String newFileName= UUID.randomUUID().toString();
        int index=fileName.lastIndexOf(".");
        newFileName=newFileName+fileName.substring(index);

        File filePath=new File("d:\\upload");
        filePath.mkdir();
        File targetFile = new File(filePath, newFileName);
        // 保存文件到指定路径
        try {
            file.transferTo(targetFile);
            return "images/"+newFileName;
        } catch(IOException e) {
            e.printStackTrace();
            return "文件上传失败！\n\r";
        }
    }

}
